package cn.aspart.validation.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author aspart
 * @date 2020/10/21
 */
@Slf4j
@RestControllerAdvice
public class ControllerAdviceHandler {

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public Object handleMethodMethodArgumentNotValidException(MethodArgumentNotValidException manve) {
    BindingResult bindingResult = manve.getBindingResult();
    StringBuilder sb = new StringBuilder();
    if (bindingResult.hasErrors()) {
      List<ObjectError> allErrors = bindingResult.getAllErrors();
      allErrors.forEach(err -> sb.append(err.getDefaultMessage()).append(" | "));
    }

    return sb.toString().substring(0, sb.toString().lastIndexOf(" | "));
  }
}
